<?php
namespace core\qiniuyun;

use \core\qiniuyun\lib\Sign;

/**
 * 七牛云身份验证类
 */
class realCard
{
    //身份证信息
    private $card_name;
    private $card_no;

    private $AccessKey;

    private $SecretKey;

    //身份证二要素
    private $url_idcard = 'https://idcard-auth.qiniuapi.com/idcard_auth';

    //身份证识别
    private $url_idcard_ocr = 'https://ocr-idcard.qiniuapi.com/ocr-idcard';

    //人脸比对
    private $url_facecompare = 'https://face-piclive.qiniuapi.com/facecompare';

    //照片活体检测
    private $url_picturelive = 'https://face-piclive.qiniuapi.com/picturelive';

    //手机三要素
    private $url_mobile = 'https://ap-gate-z0.qiniuapi.com/faceref/threemeta/check';

    private $auth = null;

    /**
     * 构造函数
     * @param array $config 配置信息
     */
    public function __construct($config = [])
    {

        $this->AccessKey = isset($config['AccessKey']) ? $config['AccessKey'] : null;
        $this->SecretKey = isset($config['SecretKey']) ? $config['SecretKey'] : null;
        if (empty($this->AccessKey)) {
            throw new \Exception("AccessKey不能为空！");
        }

        if (empty($this->SecretKey)) {
            throw new \Exception("SecretKey不能为空！");
        }
        return;
    }

    /**
     * 身份证二要素
     * @param  array $options 参数选项
     */
    public function checkIdCard($options = [])
    {
        if (empty($options['cert_name'])) {
            throw new \Exception("身份证姓名不能为空！");
        }

        if (empty($options['cert_no'])) {
            throw new \Exception("身份证号码不能为空！");
        }

        $Post = [
            'cert_name' => $options['cert_name'],
            'cert_no'   => $options['cert_no'],
        ];

        $body   = json_encode($Post);
        $header = $this->getAuthorizationV2($this->url_idcard, $body);
        $text   = $this->getResponse($this->url_idcard, $body, $header);
        $result = json_decode($text, true);
        if (is_array($result)) {
            if (preg_match('/ok/i', $result['result_code'])) {
                return ['code' => 0, 'msg' => $result['result_msg'], 'data' => $result];
            } else {
                return ['code' => -1, 'msg' => $result['result_msg']];
            }
        } else {
            return ['code' => -1, 'msg' => '接口返回解析失败，' . htmlspecialchars($text)];
        }

    }

    /**
     * 人脸比对
     * @param  array $options 参数选项
     */
    public function checkFaceCompare($options = [])
    {
        if (empty($options['image_base64_a'])) {
            throw new \Exception("图片a数据不能为空！");
        }

        if (empty($options['image_base64_b'])) {
            throw new \Exception("图片b数据不能为空！");
        }

        $Post = [
            'data_uri_a' => $options['image_base64_a'],
            'data_uri_b' => $options['image_base64_b'],
            'maxface_A'  => true,
            'maxface_B'  => true,
        ];

        $body   = json_encode($Post);
        $header = $this->getAuthorizationV2($this->url_facecompare, $body);
        $text   = $this->getResponse($this->url_facecompare, $body, $header);
        $result = json_decode($text, true);
        if (is_array($result)) {
            if (preg_match('/ok/i', $result['result_code'])) {
                return ['code' => 0, 'msg' => $result['result_msg'], 'data' => $result];
            } else {
                return ['code' => -1, 'msg' => $result['result_msg']];
            }
        } else {
            return ['code' => -1, 'msg' => '接口返回解析失败，' . htmlspecialchars($text)];
        }
    }

    /*
     * 照片活体检测
     */
    public function checkFacePiclive($options = [])
    {
        if (!isset($options['image_base64_list']) || !is_array($options['image_base64_list']) || count($options['image_base64_list']) == 0) {
            throw new \Exception("要检测的图片列表不能为空！");
        }

        $frames = [];
        foreach ($options['image_base64_list'] as $key => $value) {
            $frames[] = [
                'image_b64' => $value,
                'image_id'  => md5($value),
                'quality'   => 63,
            ];
        }

        $Post = [
            'frames' => json_encode($frames),
        ];

        $body   = json_encode($Post);
        $header = $this->getAuthorizationV2($this->url_picturelive, $body);
        $text   = $this->getResponse($this->url_picturelive, $body, $header);
        $result = json_decode($text, true);
        if (is_array($result)) {
            if (preg_match('/ok/i', $result['result_code'])) {
                return ['code' => 0, 'msg' => $result['result_msg'], 'data' => $result];
            } else {
                return ['code' => -1, 'msg' => $result['result_msg']];
            }
        } else {
            return ['code' => -1, 'msg' => '接口返回解析失败，' . htmlspecialchars($text)];
        }
    }

    /*
     * 验证手机三要素
     */
    public function checkMobile($options = [])
    {
        if (empty($options['cert_name'])) {
            throw new \Exception("身份证姓名不能为空！");
        }

        if (empty($options['cert_no'])) {
            throw new \Exception("身份证号码不能为空！");
        }

        if (empty($options['mobile'])) {
            throw new \Exception("手机号码不能为空！");
        }

        $Post = [
            'cert_name' => $cert_name,
            'cert_no'   => $cert_no,
            'mobile'    => $mobile,
        ];
        $body   = json_encode($Post);
        $header = $this->getAuthorizationV2($this->url_mobile, $body);
        $text   = $this->getResponse($this->url_mobile, $body, $header);
        $result = json_decode($text, true);
        if (is_array($result)) {
            if (preg_match('/ok/i', $result['result_code'])) {
                return ['code' => 0, 'msg' => $result['result_msg'], 'data' => $result];
            } else {
                return ['code' => -1, 'msg' => $result['result_msg']];
            }
        } else {
            return ['code' => -1, 'msg' => '接口返回解析失败，' . htmlspecialchars($text)];
        }
    }

    /**
     * 解析header
     * @param  array  $data header数据
     * @return array
     */
    private function getAuthorizationV2($url, $method = 'GET', $body = null, $contentType = 'application/json')
    {
        $auth   = new Sign($this->AccessKey, $this->SecretKey);
        $header = $auth->authorizationV2($url, $method, $body, $contentType);
        return $this->parseHeader($header);
    }

    /**
     * 解析header
     * @param  array  $data header数据
     * @return array
     */
    private function parseHeader($data = [])
    {
        $header = [];
        foreach ($data as $key => $value) {
            $header[] = "{$key}: {$value}";
        }
        return $header;
    }

    /**
     * 获取模拟请求结果
     * @param  string  $url     请求链接
     * @param  integer $post    请求内容
     * @param  integer $timeout 超时时间
     * @return string
     */
    public function getResponse($url = '', $post = 0, $header = [], $timeout = 30)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if (!is_array($header)) {
            $header   = [];
            $header[] = 'Content-Type: application/json';
        }
        $header[] = 'Host: ' . parse_url($url)['host'];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $result = curl_exec($ch);
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // if ($httpCode != 200) {
        //     $result = json_encode(['code' => -1, 'msg' => '[HttpCode:' . $httpCode . ']' . curl_error($ch)]);
        // }
        curl_close($ch);
        return $result;
    }
}
